<template>
  <view class="searchAdd">
    <topTitle />
    <view class="com">
      <up-avatar
        mode="aspectFill"
        :src="friendInfo.picture"
        size="70"
      ></up-avatar>
      <view>{{ friendInfo.nick_name }}</view>
      <up-textarea
        v-if="!info"
        :disabled="friendInfo.type != 0"
        v-model="describe"
        maxlength="100"
        height="80"
      ></up-textarea>
      <view v-if="info">
        <up-button text="发消息" @tap="goDetail" type="primary"></up-button>
      </view>
      <view v-if="!info">
        <up-button
          v-if="friendInfo.type == 0"
          :text="isSend ? '已發送' : '+添加好友'"
          :disabled="isSend"
          @tap="friendApplyAddFn"
          type="primary"
        ></up-button>
        <!-- 通過好友申請 -->
        <up-button
          v-if="friendInfo.type == 1"
          text="同意"
          @tap="friendApplyApproveFn"
          type="primary"
        ></up-button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance } from "vue";
import { FriendApplyAdd, FriendApplyApprove } from "@/api/ImApi";
const instance = getCurrentInstance()?.appContext.config.globalProperties;
import { onLoad } from "@dcloudio/uni-app";
let userInfo = ref<any>();
userInfo.value = uni.getStorageSync("userInfo");
let friendInfo = ref<any>();
let describe = ref<string>();
let isSend = ref<boolean>(false);
let remarks = "我是" + userInfo.value.nick_name;
onLoad((option: any) => {
  const query = decodeURIComponent(option.searchValue);
  friendInfo.value = JSON.parse(query);
  describe.value = remarks;
  console.log(friendInfo.value);
  getFriendList();
});

let info = ref<any>();
// 判断对方是我的好友
const getFriendList = async () => {
  let friendList = await instance?.$db.loadData("friendList", {
    user_id: friendInfo.value.user_id,
  });
  if (friendList?.length) {
    info.value = friendList[0];
    console.log(info.value);
  } else {
    info.value = null;
  }
};

// 添加好友
const friendApplyAddFn = async () => {
  await FriendApplyAdd({
    id_no: friendInfo.value.id_no,
    describe: describe.value || remarks,
    loading: 1,
  });
  isSend.value = true;
  uni.showToast({ title: "好友邀请发送成功", icon: "none" });
};
// 好友申請通過;
const friendApplyApproveFn = async () => {
  await FriendApplyApprove({
    id: friendInfo.value.Id,
    loading: 1,
  });
  isSend.value = true;
  instance?.goBack(1, "好友申請通過");
};
// 进入聊天
const goDetail = async () => {
  instance?.goTo(
    "/pages/chat/chat?user_id=" +
      info.value.user_id +
      "&item=" +
      encodeURIComponent(JSON.stringify(info.value))
  );
};
</script>
<style scoped lang="scss">
@import "../../static/scss/addFriend.scss";
</style>
